<template>
    <view class="hls-player-container">
        <video id="video1" class="hls-player" :is-live="props.live" :poster="props.poster || '/static/logo1.png'"
            controls autoplay muted playsinline />
        <view v-if="loading" class="loading">视频加载中...</view>
        <view v-if="error" class="error">视频加载失败: {{ errorMessage }}</view>
    </view>
</template>

<script setup>
import { onMounted, ref, watch, nextTick, onBeforeUnmount } from 'vue'
import Hls from 'hls.js'

const props = defineProps({
    src: String,
    poster: String,
    live: Boolean
})

// const video1 = ref(null)
const loading = ref(false)
const error = ref(false)
const errorMessage = ref('')
let hls = null

onMounted(() => {
    console.log('HLS播放器已挂载，开始初始化')
    nextTick(() => play())
})

watch(() => props.src, (newSrc, oldSrc) => {
    console.log('视频源发生变化:', oldSrc, '->', newSrc)
    if (newSrc && newSrc !== oldSrc) {
        hls?.destroy()
        nextTick(() => play())
    }
})

function play() {
    if (!props.src) {
        console.warn('视频源为空')
        // error.value = true
        // errorMessage.value = '视频源为空'
        return
    }

    console.log('开始播放视频:', props.src)
    loading.value = true
    error.value = false

    const el = document.getElementById('video1')
    const nativeVideoEl = el.querySelector('video'); 
    console.log(nativeVideoEl);
    if (!nativeVideoEl) {
        console.error('视频元素未找到（请检查ref是否正确）');
        error.value = true;
        errorMessage.value = '播放器初始化失败';
        loading.value = false;
        return;
    }

    // 检查 HLS.js 是否可用
    if (typeof Hls === 'undefined') {
        console.error('HLS.js 未正确导入')
        error.value = true
        errorMessage.value = 'HLS播放器库未加载'
        loading.value = false
        return
    }

    if (Hls.isSupported()) {
        console.log('使用 HLS.js 播放')
        try {
            hls = new Hls({
                enableWorker: false, // 在某些环境下禁用worker
                lowLatencyMode: false, // 关闭低延迟模式（减少复杂逻辑）
                backBufferLength: 30, // 降低缓冲长度
                maxBufferLength: 30,
                maxMaxBufferLength: 60
            })

            hls.loadSource(props.src)
            hls.attachMedia(nativeVideoEl)// 绑定视频元素

            hls.on(Hls.Events.MANIFEST_PARSED, () => {
                console.log('视频清单解析完成，开始播放')
                loading.value = false
                nativeVideoEl.play().catch(err => {
                    console.warn('自动播放失败（浏览器政策限制）:', err);
                    error.value = true; // 显示提示
                    // 提示用户手动点击播放
                    errorMessage.value = '请点击播放器开始播放';
                })
            })

            hls.on(Hls.Events.ERROR, (event, data) => {
                console.error('HLS 错误详情:', {
                    type: data.type,
                    details: data.details,
                    fatal: data.fatal,
                    error: data.error?.message || data.error, // 打印具体错误堆栈
                    url: props.src // 同时打印当前播放地址
                });
                error.value = true
                errorMessage.value = `播放错误: ${data.type} - ${data.details}`
                loading.value = false
                uni.showToast({
                    title: `直播加载失败: ${data.details}`,
                    icon: 'none',
                    duration: 3000
                })
            })

        } catch (err) {
            console.error('HLS初始化失败:', err)
            error.value = true
            errorMessage.value = err.message
            loading.value = false
        }
    } else if (nativeVideoEl.canPlayType('application/vnd.apple.mpegurl')) {
        // Safari 原生支持
        console.log('使用 Safari 原生 HLS 播放')
        nativeVideoEl.src = props.src
        nativeVideoEl.addEventListener('loadedmetadata', () => {
            console.log('视频元数据加载完成')
            loading.value = false
            nativeVideoEl.play().catch(err => {
                console.error('Safari自动播放失败:', err)
            })
        })
        nativeVideoEl.addEventListener('error', () => {
            console.error('Safari视频加载错误')
            error.value = true
            errorMessage.value = 'Safari视频加载失败'
            loading.value = false
        })
    } else {
        console.error('浏览器不支持 HLS')
        error.value = true
        errorMessage.value = '当前浏览器不支持HLS视频格式'
        loading.value = false
        uni.showToast({
            title: '浏览器不支持 HLS 视频格式',
            icon: 'none',
            duration: 3000
        })
    }
}

onBeforeUnmount(() => {
    console.log('HLS播放器即将销毁')
    if (hls) {
        hls.destroy()
        hls = null
    }
})
</script>

<style scoped>
.hls-player-container {
    position: relative;
    width: 100%;
    height: 100%;
}

.hls-player {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
    background: #000;
}

.loading,
.error {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 20rpx 40rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
}

.error {
    background: rgba(255, 0, 0, 0.7);
}
</style>